package com.cms.ctrl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.cms.domain.Template;
import com.cms.freemarker.service.SubjectDataServiceAdaptor;
import com.cms.service.TemplateService;
import com.core.page.Pagination;
import com.core.spring.SpringFreemarkerContextPathUtil;
import com.core.util.FileUtil;
import com.core.util.PropertiesConfigUtil;
import com.core.util.UploadUtil;
import com.wxcms.domain.AccountFans;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;

/**
 * 
 */

@Controller
@RequestMapping("/template")
public class TemplateCtrl {
	
	@Autowired
	private TemplateService templateService;

//	@Autowired
//	private FreeMarkerConfigurer freemarkerConfig;
	
	@Autowired
	private SubjectDataServiceAdaptor sdsa;

	@RequestMapping(value = "/getById")
	public ModelAndView getById(String id) {
		templateService.getById(Long.valueOf(id));
		return new ModelAndView();
	}

	@RequestMapping(value = "/templateManager")
	public  ModelAndView templateManager(String id_sbj,Pagination<AccountFans> pagination){
		ModelAndView modelAndView = new ModelAndView("subject/template/templateManager");
		List pageList = templateService.getList(Long.valueOf(id_sbj), pagination.getPageNum(), pagination.getPageSize());
		if(pageList!=null && pageList.size()>0){
			pagination.setItems(pageList);
			pagination.setTotalItemsCount(templateService.getRowCount(Long.valueOf(id_sbj)));
		}
		modelAndView.addObject("id_sbj", id_sbj);
		modelAndView.addObject("pagination", pagination);
		modelAndView.addObject("cur_nav", "subject");
		return modelAndView;
	}
	
//	@RequestMapping(value = "/templateManager")
//	public ModelAndView templateManager(String id_sbj) {
//		ModelAndView modelAndView = new ModelAndView("subject/template/templateManager");
//		modelAndView.addObject("id_sbj", id_sbj);
//		List<Template> pageList = templateService.getList(Long.valueOf(id_sbj));
//		modelAndView.addObject("pageList", pageList);
//		modelAndView.addObject("cur_nav", "template");
//		return modelAndView;
//	}

	@RequestMapping(value = "/toTemplateMerge")
	public ModelAndView toTemplateMerge(Template entity, String id_sbj) {
		ModelAndView mv = new ModelAndView("subject/template/templateMerge");
		mv.addObject("cur_nav", "template");
		mv.addObject("id_sbj", id_sbj);
		if (entity.getId() != null) {
			Template temp = templateService.getById(Long.valueOf(entity.getId().toString()));
			if(temp.getCategory()==null){
				temp.setCategory("template");
			}
			mv.addObject("entity", temp);
		} else {
			Template temp = new Template();
			temp.setIdSbj(Long.valueOf(id_sbj));
			temp.setCategory("template");
			mv.addObject("entity", temp);
		}
		return mv;
	}

	@RequestMapping(value = "/temp/{folderName}/index", method = RequestMethod.GET)
	public ModelAndView temp(HttpServletRequest request, @PathVariable String folderName) {
		ModelAndView mv = new ModelAndView("subject/template/temp/".concat(folderName).concat("/index"));
		
		Map<String, String> map = (Map<String, String>) RequestContextUtils.getInputFlashMap(request);
		if(map!=null){
			for (Map.Entry<String, String> entry : map.entrySet()) {
				mv.addObject(entry.getKey(), entry.getValue());
			}
		}
		
		for (Object key : request.getParameterMap().keySet()) {
			String value =  request.getParameter(key.toString());
			mv.addObject(key.toString(), value);
		}
		
		return mv;
	}

	@RequestMapping(value = "/getTempByKey")
	public ModelAndView getTempByKey(HttpServletRequest request, RedirectAttributes attributes, String keyWord) {

		Template temp = templateService.getByKey(keyWord);
		if (temp == null) {
			ModelAndView mv = new ModelAndView("common/failure");
			mv.addObject("failureMsg", "没有查到对应关键字的模板，请确认关键字是否正确!");
			return mv;
		}
		
//		mv.addObject("temp", temp);
//		attributes.addFlashAttribute(request.getParameterMap());
		StringBuffer parameter_buf =new StringBuffer();
		for (Object key : request.getParameterMap().keySet()) {
			String value =  request.getParameter(key.toString());
			attributes.addFlashAttribute(key.toString(), value);
			
			parameter_buf.append("&");
			parameter_buf.append(key.toString());
			parameter_buf.append("=");
			parameter_buf.append(value);
		}
		String parameter_s = "";
		if(parameter_buf.length()>0 && parameter_buf.indexOf("&")==0){
			parameter_s = "?".concat(parameter_buf.substring(1));
		}
		String url_redirect = "redirect:/template/temp/".concat(temp.getDirname()).concat("/index.html").concat(parameter_s);
		ModelAndView mv = new ModelAndView(url_redirect);
		
		return mv;
	}
	
//	@RequestMapping(value = "/getResourceByKey")
//	public ModelAndView getResourceByKey(HttpServletRequest request, RedirectAttributes attributes, String keyWord) {
//
//		Template temp = templateService.getByKey(keyWord);
//		if (temp == null) {
//			ModelAndView mv = new ModelAndView("common/failure");
//			mv.addObject("failureMsg", "没有查到对应关键字的模板，请确认关键字是否正确!");
//			return mv;
//		}
//		ModelAndView mv = new ModelAndView("redirect:/template/temp/".concat(temp.getDirname()).concat("/images"));
////		mv.addObject("temp", temp);
//		return mv;
//	}
	
	@RequestMapping(value = "/tempEditer")
	public ModelAndView tempEditer(HttpServletRequest request, String id) {
		ModelAndView mv = new ModelAndView("subject/template/tempEditer");
		Template temp = templateService.getById(Long.valueOf(id));
		mv.addObject("id", id);
		
		String realPath = request.getSession().getServletContext().getRealPath("/");
		String tempPath = templateService.TEMP_ROOT.concat(temp.getDirname());
		String filePath = realPath.concat(tempPath).concat("/index.html");
		
		String tempContext = FileUtil.readFile(filePath);
		mv.addObject("tempContext", tempContext);
		return mv;
	}
	
	@RequestMapping(value = "/tempEditerSave")
	public ModelAndView tempEditerSave(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("subject/template/tempEditer");
		String id = request.getParameter("id");
		String fileContext  = request.getParameter("tempContext");
		
		Template temp = templateService.getById(Long.valueOf(id));
		mv.addObject("id", id);
		
		String realPath = request.getSession().getServletContext().getRealPath("/");
		String tempPath = templateService.TEMP_ROOT.concat(temp.getDirname());
		String filePath = realPath.concat(tempPath).concat("/index.html");
		
		FileUtil.writeFile(filePath, fileContext);
		String tempContext = FileUtil.readFile(filePath);
		mv.addObject("tempContext", tempContext);
		return mv;
	}
	
	@RequestMapping(value = "/tempDownload")
	public ModelAndView tempDownload(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
		//构建压缩文件
		Template temp = templateService.getById(Long.valueOf(id));
		String dirName = temp.getDirname();
		String tempPath = templateService.TEMP_ROOT.concat(dirName);
		String resourcePath = templateService.RESOURCE_ROOT.concat(dirName);
		String realPath = request.getSession().getServletContext().getRealPath("/");
		
		File[] files =null;
		
		File resourceFolder = new File(realPath.concat(resourcePath));
		if(resourceFolder.exists()){

			files = new File[2];
			files[1] = new File(realPath.concat(resourcePath));
		}else{
			files = new File[1];
		}
		files[0] = new File(realPath.concat(tempPath));
		
		String zipFileName = dirName.concat(".zip");
		String zipFilePath = realPath.concat(resourcePath).concat("/").concat(zipFileName);
		File zipFile = new File(zipFilePath);
		if(zipFile.exists()){
			zipFile.delete();
		}
		FileUtil.WrapZipFilesByAnt(files, zipFilePath);
		
		//输出文件
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
		try {
			
			response.setContentType("text/html;charset=utf-8");
			request.setCharacterEncoding("UTF-8");
			
			long fileLength = new File(zipFilePath).length();
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename=" + new String(zipFileName.getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(zipFilePath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
			if(zipFile.exists())
				zipFile.delete();
		}

		return null;
	}

	@RequestMapping(value = "/doTemplateMerge")
	public ModelAndView doTemplateMerge(HttpServletRequest request, Template entity, @RequestParam(value = "zipFile", required = false) MultipartFile file)
			throws IllegalStateException, IOException {
		String contextPath = SpringFreemarkerContextPathUtil.getBasePath(request);
		// String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + contextPath;
		String realPath = request.getSession().getServletContext().getRealPath("/");

		// 读取配置文件上传的路径
		if (PropertiesConfigUtil.getProperty("upload.properties", "upload.path") != null) {
			realPath = PropertiesConfigUtil.getProperty("upload.properties", "upload.path").toString();
		}
		String fileName = file.getOriginalFilename();
		if (!fileName.equals("") && !(fileName.toLowerCase().endsWith(".zip") || fileName.toLowerCase().endsWith(".html"))) {
			ModelAndView mv = new ModelAndView("common/failure");
			mv.addObject("failureMsg", "请上传html或zip类型文件!");
			return mv;
		}
		
		if (entity.getKeyWord() == null || "".equals(entity.getKeyWord().replaceAll(" ", ""))) {
			ModelAndView mv = new ModelAndView("common/failure");
			mv.addObject("failureMsg", "关键字不能为空，请设置关键字!");
			return mv;
		}
		
		Template temp = templateService.getByKey(entity.getKeyWord());
		if (temp != null && !temp.getId().equals(entity.getId())) {
			ModelAndView mv = new ModelAndView("common/failure");
			mv.addObject("failureMsg", "关键字设置重复，请修改关键字!");
			return mv;
		}
		
//		if (file.getSize() > 10000000) {
//			ModelAndView mv = new ModelAndView("common/failure");
//			mv.addObject("failureMsg", "上传文件过大!");
//			return mv;
//		}
		
		//上传文件处理
		if(!fileName.equals("")){
			
			String folderName = UUID.randomUUID().toString();
			if(entity.getDirname()!=null && !entity.getDirname().equals("")){
				folderName = entity.getDirname();
			}
			
			String tempPath = templateService.TEMP_ROOT.concat(folderName);
			String resourcePath = templateService.RESOURCE_ROOT.concat(folderName);
			
			if(entity.getDirname()!=null && !entity.getDirname().equals("")){
				FileUtil.deleteFiles(realPath.concat(tempPath));
				if(fileName.toLowerCase().endsWith(".zip")){
					FileUtil.deleteFiles(realPath.concat(resourcePath));
				}
			}
			
			if(fileName.toLowerCase().endsWith(".zip")){
				
				UploadUtil.doUploadFile(realPath, resourcePath.concat("/"), file);
				File resourceFile = new File(realPath.concat(resourcePath).concat("/").concat(fileName));
				if (resourceFile.exists() && resourceFile.isFile()) {
					boolean b = FileUtil.unWrapZipZipFiles(resourceFile.getPath(), realPath.concat(resourcePath).concat("/"));
					if (b) {
						resourceFile.delete(); // 解压后删除压缩文件
						
						File tempFile = new File(realPath.concat(resourcePath).concat("/index.html"));
						if(tempFile.exists() && tempFile.isFile()){
							FileUtil.Move(tempFile, realPath.concat(tempPath).concat("/"));
						}
					}
				}
				
			}else{
				UploadUtil.doUploadFile(realPath, tempPath.concat("/"), file);
			}
			
			entity.setDirname(folderName);
		}
	
		
		if (entity.getId() == null) {
			templateService.add(entity);
			
		} else {
			templateService.update(entity);
		}
		return new ModelAndView("redirect:/template/templateManager.html?id_sbj=".concat(entity.getIdSbj().toString()));
	}

	@RequestMapping(value = "/deleteTemplate")
	public ModelAndView deleteTemplate(Template entity, HttpServletRequest request) {
		Template temp = new Template();
		temp = templateService.getById(entity.getId());
		String dirName = temp.getDirname();
		String tempPath = templateService.TEMP_ROOT.concat(dirName);
		String resourcePath = templateService.RESOURCE_ROOT.concat(dirName);
		String realPath = request.getSession().getServletContext().getRealPath("/");
		
		FileUtil.deleteFiles(realPath.concat(tempPath));
		FileUtil.deleteFiles(realPath.concat(resourcePath));
		templateService.delete(entity);
		return new ModelAndView("redirect:/template/templateManager.html?id_sbj=".concat(temp.getIdSbj().toString()));
	}
	
	@RequestMapping(value = "/tempStaticCreate")
	public ModelAndView tempStaticCreate(HttpServletRequest request) {
		
		String realPath = request.getSession().getServletContext().getRealPath("/");
		
		String id = request.getParameter("id");
		Template temp = templateService.getById(Long.valueOf(id));
		request.setAttribute("id_sbj", "1111");
		String tempFileName = temp.getDirname();
		if (tempFileName == null || "".equals(tempFileName)) {
			ModelAndView mv = new ModelAndView("common/failure");
			mv.addObject("failureMsg", "没有查到对应的模板文件，无法进行静态化!");
			return mv;
		}
		
		String tempStaticName = temp.getKeyWord();
		if(tempStaticName==null || "".equals(tempStaticName)){
			ModelAndView mv = new ModelAndView("common/failure");
			mv.addObject("failureMsg", "没有对应的关键字，无法进行静态化!");
			return mv;
		}
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if(temp.getStaticParameters()!=null && !"".equals(temp.getStaticParameters())){
			String[] parameters = temp.getStaticParameters().split("&");
			for(String parameter:parameters){
				Object[] parameter_map = parameter.split("=");
				if(parameter_map.length==2 && parameter_map[0]!=null && parameter_map[1]!=null){
					paramMap.put(parameter_map[0].toString(),parameter_map[1]);
				}
			}
		}
		paramMap.put("sdsa", this.sdsa);
//		paramMap.put("rccontextPath",request.getSession().getServletContext().getContextPath());
		
		String tempPath = templateService.TEMP_ROOT.concat(tempFileName);
		String tempStaticPath = templateService.TEMP_STATIC_ROOT;
//		FileUtil.crateHTML(request.getSession().getServletContext(), paramMap, tempPath, "index.html", tempStaticPath, tempStaticName.concat(".htm"));
		//创建file
		FileUtil.crateHTML(paramMap, realPath.concat(tempPath), "index.html", realPath.concat(tempStaticPath), tempStaticName.concat(".htm"));
		
        
		String url_redirect = "redirect:/template/temp/static/".concat(temp.getKeyWord()).concat(".htm");
		ModelAndView mv = new ModelAndView(url_redirect);
		mv.addAllObjects(paramMap);
		return mv;
	}
	
}
